<template>
  <div>
      <standard-search-table
        ref="table"
        :fetch="submitHandler"
        :page-sizes="[10, 20, 30, 40, 50]"
        :columns="columns"
        :formOptions="formOptions"
        :handleCreate="handleCreate"
      >
        <template v-slot:actions="{row}">
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(row)"
          >编辑</el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(row)"
          >删除</el-button>
        </template>
      </standard-search-table>
      <el-dialog
        :visible="editModalVisible"
        :title="'编辑账号'"
        @close="editModalVisible=false"
      >
        <standard-form
          ref="editForm"
          :forms="editFormOptions.forms"
          :item-width="editFormOptions.itemWidth"
          :showCancelBtn="true"
          :submitBtnText="'确定'"
          :resetBtnText="'取消'"
          :form-data="editFormData"
          :handle-submit="handleSaveEditForm"
          :handle-cancel="handleCloseEditModal"
          :labelWidth="editFormOptions.labelWidth"
          :rules="editFormOptions.rules"
          :submitLoading="submitLoading"
        />
      </el-dialog>
        <el-dialog
          :visible="createModalVisible"
          :title="'新建账号'"
          @close="createModalVisible=false"
        >
        <standard-form
          ref="createForm"
          :forms="createFormOptions.forms"
          :item-width="createFormOptions.itemWidth"
          :showCancelBtn="true"
          :submitBtnText="'确定'"
          :resetBtnText="'取消'"
          :form-data="createFormData"
          :handle-submit="handleSaveCreateForm"
          :handle-cancel="handleCloseCreateModal"
          :rules="createFormOptions.rules"
          :submitLoading="submitLoading"
        />
      </el-dialog>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { AdminController } from '@/controllers/AdminController'
import { RoleAdminController } from '@/controllers/RoleAdminController'

import StandardForm from '@/components/StandardForm/index.vue'
import StandardSearchTable from '@/components/StandardSearchTable/index.vue'
import { AdminQueryEntity } from '@/controllers/definitions/AdminQueryEntity'
import { AdminResponseEntity } from '@/controllers/definitions/AdminResponseEntity'
import { Pagination } from 'element-ui'
import { Admin } from '@/controllers/definitions/Admin'

const adminController = new AdminController()
const roleController = new RoleAdminController()

@Component({
  name: 'AccountListPage',
  components: {
    StandardForm,
    StandardSearchTable
  }
})
export default class extends Vue {
  private formOptions = {
    inline: true,
    submitBtnText: '查询',
    showResetBtn: true,
    labelWidth: '80px',
    forms: [
      {
        prop: 'name',
        label: '姓名',
        clearable: true
      },
      {
        prop: 'mobile',
        label: '手机号',
        clearable: true
      },
      {
        prop: 'roleId',
        label: '角色',
        type: 'select',
        clearable: true,
        options: [
          { value: '1', label: '超级管理员' },
          { value: '2', label: '北区管理员' },
          { value: '3', label: '南区管理员' },
          { value: '4', label: '车辆检测员' }
        ]
      }
    ],
    rules: {}
  }

  private editFormOptions = {
    inline: true,
    submitBtnText: '查询',
    showResetBtn: true,
    labelWidth: '80px',
    forms: [
      {
        prop: 'name',
        label: '姓名',
        rules: [
          {
            required: true,
            message: '姓名为必填项'
          }
        ]
      },
      {
        prop: 'mobile',
        label: '手机号',
        rules: [
          {
            required: true,
            message: '手机号为必填项'
          }
        ]
      },
      {
        prop: 'roleId',
        label: '角色',
        type: 'select',
        options: [
          { value: '1', label: '超级管理员' },
          { value: '2', label: '北区管理员' },
          { value: '3', label: '南区管理员' },
          { value: '4', label: '车辆检测员' }
        ],
        rules: [
          {
            required: true,
            message: '角色为必选项'
          }
        ]
      }
    ],
    rules: {}
  }

  private createFormOptions = {
    labelWidth: '80px',
    forms: [
      {
        prop: 'name',
        label: '姓名',
        rules: [
          {
            required: true,
            message: '姓名为必填项'
          }
        ]
      },
      {
        prop: 'mobile',
        label: '手机号',
        rules: [
          {
            required: true,
            message: '手机号为必填项'
          }
        ]
      },
      {
        prop: 'roleId',
        label: '角色',
        type: 'select',
        options: [
          { value: '1', label: '超级管理员' },
          { value: '2', label: '北区管理员' },
          { value: '3', label: '南区管理员' },
          { value: '4', label: '车辆检测员' }
        ],
        rules: [
          {
            required: true,
            message: '角色为必选项'
          }
        ]
      },
      {
        prop: 'password',
        label: '密码',
        inputType: 'password',
        rules: [
          {
            required: true,
            message: '密码为必填项'
          },
          {
            pattern: /^[0-9a-zA-Z]{6,20}$/gi,
            message: '请输入6-20位字母或者数字的初始密码'
          }
        ]
      }
    ],
    rules: {}
  }

  private columns = [
    { prop: 'name', label: '姓名' },
    { prop: 'mobile', label: '手机号' },
    {
      prop: 'roleId',
      label: '角色',
      minWidth: 180,
      render: (row: any) => {
        const map: any = {
          1: '超级管理员',
          2: '北区管理员',
          3: '南区管理员',
          4: '车辆检测员'
        }
        return map[row.roleId]
      }
    },
    {
      prop: 'actions',
      label: '操作',
      slotName: 'actions',
      width: 240
    }
  ]

  private tableData: AdminResponseEntity[] = []
  private dataCount = 0
  private editModalVisible = false
  private createModalVisible = false
  private editFormData = {};
  private createFormData = {};
  private submitLoading = false;

  private async submitHandler(params: any, pagination: any) {
    console.log(params)
    const result = await adminController.pageUsingPOST({
      ...params,
      page: pagination.pageIndex,
      limit: pagination.pageSize
    } as AdminQueryEntity)
    if (result.code === 200) {
      this.tableData = result.data?.records || []
      this.dataCount = result.data?.total || 0
    }
    return {
      list: this.tableData,
      total: this.dataCount
    }
  }

  private async handleEdit(row: Admin) {
    this.editFormData = {
      id: row.id,
      name: row.name,
      roleId: row.roleId,
      mobile: row.mobile
    }
    this.editModalVisible = true
  }

  private async handleCreate() {
    this.createFormData = {}
    this.createModalVisible = true
  }

  private async handleDelete(row: any) {
    this.$confirm('你确定要删除吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async() => {
      const result = await adminController.deleteUsingDELETE(row.id)
      if (result.code === 200) {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.reload()
      } else {
        this.$message({
          type: 'error',
          message: result.message as string
        })
      }
    }).catch(() => {
      this.$message({
        type: 'info',
        message: '已取消删除'
      })
    })
  }

  private async handleSaveEditForm() {
    this.submitLoading = true
    try {
      const result = await adminController.updateUsingPUT({
        ...this.editFormData
      } as Admin)
      if (result.code === 200) {
        this.$message({
          message: '更新成功',
          type: 'success'
        })
        this.editModalVisible = false
        this.reload()
      } else {
        this.$message({
          message: result.message as string,
          type: 'error'
        })
      }
      this.submitLoading = false
    } catch (error) {
      console.log(error)
      this.submitLoading = false
    }
  }

  private async handleCloseEditModal() {
    this.editModalVisible = false
  }

  private async handleSaveCreateForm() {
    console.log(this.createFormData)
    this.submitLoading = true
    try {
      const result = await adminController.insertUsingPOST({
        ...this.createFormData
      } as Admin)
      if (result.code === 200) {
        this.$message({
          message: '新增成功',
          type: 'success'
        })
        this.createModalVisible = false
        this.reload()
      } else {
        this.$message({
          message: result.message as string,
          type: 'error'
        })
      }
      this.submitLoading = false
    } catch (error) {
      console.log(error)
      this.submitLoading = false
    }
  }

  private async handleCloseCreateModal() {
    this.createModalVisible = false
  }

  private reload() {
    const table = this.$refs.table as StandardSearchTable
    table.reload()
  }
}
</script>
